/**
 * Created by moc on 2016/4/5.
 */

var path = require('path')
var fs = require('fs')

var ctype = {
    ".js": "application/x-javascript",
    ".css": "text/css",
    ".jpg": "image/jpeg",
    ".html": "text/html"
}

exports = module.exports = function (root) {
    root = path.resolve(root)
    return function (req, res, next) {
        var file = req.originalUrl.slice(req.baseUrl.length + 1);

        file = path.resolve(root, file);
        if (file == root) {
            next()
        } else {
            if (file.length >= root.length && file.substr(0, root.length) == root) {
                if (fs.existsSync(file)) {
                    if (fs.lstatSync(file).isDirectory()) {
                        file = file + "//index.html"
                    }
                    if (fs.existsSync(file) == false) {
                        next()
                        return
                    }

                    var stream = fs.createReadStream(file);
                    var ext = path.extname(file)
                    if (ctype[ext] != undefined) {
                        res.writeHead(200, {"Content-Type": ctype[ext]})
                    } else {
                        res.writeHead(200, {"Content-Type": "application/octet-stream"})
                    }
                    stream.pipe(res)
                    console.log(file)
                    console.log(path.extname(file))
                } else {
                    next()
                }
            } else {
                res.end("fuck you")
            }
        }
    }
}

